import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:markdown_widget/markdown_widget.dart';

import '../../../../common/models/ai/index.dart';
import '../../../../common/style/icon_font.dart';
import '../../../../common/utils/o2_api_manager.dart';
import '../../../../common/widgets/im_bubble_shape.dart';
import '../../../home/im/im_chat/widgets/chat_behavior.dart';
import '../controller.dart';
import 'msg_bussiness_body.dart';

class AIChatMsgListWidget extends GetView<AiController> {
  const AIChatMsgListWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(right: 10.0, left: 10.0),
        child: Obx(() => ScrollConfiguration(
            behavior: const ChatScrollBehavior(),
            child: Align(
                alignment: Alignment.topCenter,
                child: ListView.separated(
                    padding: const EdgeInsets.only(bottom: 10),
                    // reverse: true, // 反转
                    shrinkWrap: true,
                    controller: controller.msgListScrollController,
                    itemBuilder: (BuildContext context, int index) {
                      // if (index == controller.state.chatInfoList.length) {
                      //   return O2UI.noResultView(context);
                      // }
                      AIChatInfo info = controller.state.chatInfoList[index];
                      return _itemView(context, info);
                    },
                    separatorBuilder: (context, index) {
                      return const SizedBox(height: 1);
                    },
                    itemCount: controller.state.chatInfoList.length)))));
  }

  Widget _itemView(BuildContext context, AIChatInfo info) {
    return Column(
      children: [
        const SizedBox(height: 10),
        sendListItemView(context, info),
        const SizedBox(height: 10),
        receivedLisItemView(context, info)
      ],
    );
  }

  // 接收到的消息格式
  Widget receivedLisItemView(BuildContext context, AIChatInfo info) {
    return Padding(
        padding: const EdgeInsets.only(right: 16.0, top: 5, bottom: 5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (controller.state.config.value?.appIconUrl?.isNotEmpty == true)
              networkImageView(),
            Expanded(
                flex: 1,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 10),
                    (info.id == null || info.id?.isEmpty == true)
                        ? Container(
                            padding: const EdgeInsets.all(5),
                            child: Row(
                              children: [
                                Image.asset(
                                  'assets/gif/loading.gif',
                                  width: 24,
                                  height: 24,
                                ),
                                const SizedBox(width: 5),
                                Text('ai_chat_start_loading'.tr,
                                    style:
                                        Theme.of(context).textTheme.bodySmall)
                              ],
                            ))
                        : Padding(
                            padding: const EdgeInsets.only(
                                right: 0, left: 10, top: 10, bottom: 5),
                            child: receivedContentView(context, info))
                  ],
                ))
          ],
        ));
  }

  Widget receivedContentView(BuildContext context, AIChatInfo info) {
    final content = info.content ?? '';
    if (content.contains('\$\$mcp\$\$')) {
      return AIChatMsgBodyView(info: info);
    } else {
      return _markdownView(info.content ?? '');
    }
  }

  Widget _markdownView(String mdContent) {
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: MarkdownGenerator().buildWidgets(mdContent,
            config: MarkdownConfig(configs: [
              const PConfig(textStyle: TextStyle(fontSize: 14)),
              const H1Config(
                  style: TextStyle(
                fontSize: 24,
                height: 40 / 32,
                fontWeight: FontWeight.bold,
              )),
              const H2Config(
                  style: TextStyle(
                fontSize: 20,
                height: 30 / 24,
                fontWeight: FontWeight.bold,
              )),
              const H3Config(
                  style: TextStyle(
                fontSize: 18,
                height: 25 / 20,
                fontWeight: FontWeight.bold,
              )),
              LinkConfig(
                style: const TextStyle(
                    fontSize: 16,
                    color: Color(0xff0969da),
                    decoration: TextDecoration.underline),
                onTap: (url) => controller.clickOpenUrl(url),
              ),
            ])));
  }

  Widget networkImageView() {
    String url =
        '${O2ApiManager.instance.webBaseUrl()}/${controller.state.config.value!.appIconUrl}';
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    return CachedNetworkImage(
      imageUrl: url,
      httpHeaders: headers,
      width: 42,
      height: 42,
      fit: BoxFit.fill,
    );
  }

  // 发送的消息格式
  Widget sendListItemView(BuildContext context, AIChatInfo info) {
    return SizedBox(
        width: double.infinity,
        child: Padding(
            padding: const EdgeInsets.only(left: 50, top: 5, bottom: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    flex: 1,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        const SizedBox(height: 10),
                        sendItemView(info.input ?? ''),
                        if (info.materialIdList != null &&
                            info.materialIdList!.isNotEmpty)
                          Stack(
                            alignment: Alignment.topRight,
                            children: [
                              IconButton(
                                  onPressed: () =>
                                      controller.clickOpenAttachmentList(info),
                                  icon: Icon(
                                      O2IconFont.ooiconFont('ooicon-fujian'),
                                      size: 24)),
                              Padding(
                                  padding: const EdgeInsets.all(5),
                                  child: Text('${info.materialIdList!.length}'))
                            ],
                          )
                      ],
                    )),
              ],
            )));
  }

  Widget sendItemView(String input) {
    final messageTextGroup = Flexible(
        child: Row(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Flexible(
          child: Container(
            padding: const EdgeInsets.all(14),
            decoration: const BoxDecoration(
              color: Color.fromARGB(255, 0, 127, 255),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(18),
                bottomLeft: Radius.circular(18),
                bottomRight: Radius.circular(18),
              ),
            ),
            child: Text(
              input,
              style: const TextStyle(color: Colors.white, fontSize: 14),
            ),
          ),
        ),
        CustomPaint(
            painter: ImBubbleShape(const Color.fromARGB(255, 0, 127, 255))),
      ],
    ));

    return Padding(
      padding: const EdgeInsets.only(right: 10.0, left: 0, top: 15, bottom: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          const SizedBox(height: 30),
          messageTextGroup,
        ],
      ),
    );
  }
}
